////////////////////////////////////////////////////////////
// Workfile : AddressManager.cpp
// Author : Andreas Lehner
// Date : 5.11.2012
// Description : manages addresses and persons; reads files,
// links addresses with persons and writes files,
// implements interfaces IWrite and IRead IMPLEMENTATION
// Remarks : 0
// Revision : 1
////////////////////////////////////////////////////////////
#include "AddressManager.h"

//link addresses with persons
void AddressManager::LinkAddresses(){
	//temporary list of pointers of type person
	std::list<Person*> tempList;
	//initialization of iterators
	TAddressesIter adrIter = mAddresses.begin();
	TPersonsIter persIter = mPersons.begin();
	//idx used to link a persons address index to right address
	size_t idx = 0;
	//variable to get persons without address once
	bool personsWithoutAddress = true;
	//iterate over addresses
	while (adrIter != mAddresses.end()){
		//iterate over persons
		while (persIter != mPersons.end()){
			//add person to temporary list, if its index coincides to address
			if (persIter->getIndex() == idx){
				tempList.push_back(&*persIter);
			}
			if(personsWithoutAddress && persIter->getIndex() >= getNumberOfAddresses()){
				std::cout << "LinkAddresses: no address for the person with index " << persIter->getIndex() << " ..." << std::endl;
			}
			persIter++;
		}
		//add value to map
		mLink.insert(std::pair<Address*, std::list<Person*>>(&*adrIter, tempList));
		if (tempList.size() == 0){
			std::cout << "LinkAddresses: no person for the address with index " << idx << " ..." << std::endl;
		}
		tempList.clear();
		persIter = mPersons.begin();
		personsWithoutAddress = false;
		idx++;
		adrIter++;
	}
}
//push_back an address to mAddresses
void AddressManager::addAddress(Address const& adr){
	mAddresses.push_back(adr);
}
//push_back a person to mPersons
void AddressManager::addPerson(Person const& pers){
	mPersons.push_back(pers);
}
//read file: Reader -> person-reader or address-reader
void AddressManager::ReadFile(std::string const& filename, Reader *read){
	read->ReadFile(filename, this);
}
//write file: Writer -> ascii-writer or html-writer
void AddressManager::WriteAddresses(std::string const& filename, Writer *write){
	write->WriteFile(filename, this);
}
//return pointer to map mLink
IWrite::TAddressNamesMap const* AddressManager::getAddressesWithNames() const{
	return &mLink;
}

size_t AddressManager::getNumberOfAddresses() const{
	return mAddresses.size();
}
